<template>
  <div>
    <el-dialog
      title="欢迎登录free影视"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="loginFormVisible"
      width="400px"
      @close="handleCloseLoginForm"
    >
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-row :gutter="10">
          <el-col :span="16">
            <el-form-item prop="code">
              <el-input v-model="loginForm.code" placeholder="请输入验证码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <img class="captcha-img" :src="codeUrl" @click="getCode" />
          </el-col>
        </el-row>

        <!-- 记住密码 + 注册/忘记密码 -->
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
          <div style="float:right;">
            <el-link type="primary" @click="goRegister">立即注册</el-link>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            style="width:100%;"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCodeImg } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt' // 前端加密/解密函数

export default {
  name: 'Login',
  data() {
    return {
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      loginRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '用户名长度必须介于 3-20 之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '密码长度必须介于 6-20 之间',
            trigger: 'blur',
          },
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      loading: false,
    }
  },
  computed: {
    loginFormVisible() {
      return this.$store.state.user.loginFormVisible
    },
  },
  watch: {
    loginFormVisible(val) {
      if (val) {
        this.getCode() // 弹窗显示时刷新验证码
        this.getCookie() // 弹窗显示时读取 Cookie 填充账号密码
      }
    },
  },
  methods: {
    // 获取验证码
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.loginForm.uuid = res.uuid
      })
    },
    // 读取 Cookie 自动填充
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      if (username) this.loginForm.username = username
      if (password) this.loginForm.password = decrypt(password)
      this.loginForm.rememberMe = rememberMe === 'true'
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return
        this.loading = true

        // 处理记住密码
        if (this.loginForm.rememberMe) {
          Cookies.set('username', this.loginForm.username, { expires: 30 })
          Cookies.set('password', encrypt(this.loginForm.password), {
            expires: 30,
          })
          Cookies.set('rememberMe', 'true', { expires: 30 })
        } else {
          Cookies.remove('username')
          Cookies.remove('password')
          Cookies.remove('rememberMe')
        }

        this.$store
          .dispatch('Login', this.loginForm)
          .then(() => {
            // 登录成功后获取用户信息
            return this.$store.dispatch('GetInfo')
          })
          .then(() => {
            this.loading = false
            this.$store.commit('SET_LOGINFORMVISIBLE', false)
            this.$router.push({ path: '/' })
          })
          .catch(() => {
            this.loading = false
            this.getCode() // 登录失败刷新验证码
          })
      })
    },
    // 跳转注册
    goRegister() {
      this.$store.commit('SET_LOGINFORMVISIBLE', false)
      this.$store.dispatch('showRegisterForm')
    },
    handleCloseLoginForm() {
      this.$store.commit('SET_LOGINFORMVISIBLE', false)
    },
  },
}
</script>

<style scoped>
.captcha-img {
  display: block;
  width: 100%;
  height: 40px;
  cursor: pointer;
}
</style>
